package Utils;

import java.net.URLEncoder;

import com.alibaba.fastjson.JSONObject;
import com.miaodiyun.httpapidemo.common.Config;
import com.miaodiyun.httpapidemo.common.HttpUtil;

public class GetMessageCode {
	//private static String operation = "/sendSMS";//对应的API地址
	//private static String accountSid = Config.ACCOUNT_SID;
//	private static String to = "15973589010"; //改由前台传入
	private static String rod=smsCode();   //生成一个随机验证码
	//private static String smsContent = "【京东验证码】您的验证码："+rod+"，如非本人操作，请忽略此短信。";

	//创建验证码
	public static String smsCode(){
		String random=(int)((Math.random()*9+1)*100000)+"";	
		System.out.print("random验证码:"+random);
		return random;
	}
	
	//根据相应的手机号发送验证码
	public static String getCode(String phone) throws Exception{
//		String tmpSmsContent = null;
//	    try{
//	      tmpSmsContent = URLEncoder.encode(smsContent, "UTF-8");
//	    }catch(Exception e){
//	    	e.getMessage();
//	    }
		StringBuilder sb = new StringBuilder();
		sb.append("accountSid").append("=").append(Config.ACCOUNT_SID);
		sb.append("&to").append("=").append(phone);
		sb.append("&param").append("=").append(URLEncoder.encode(rod,"UTF-8"));
		sb.append("&templateid").append("=").append("247380");
//		sb.append("&smsContent").append("=").append( URLEncoder.encode("【秒嘀科技】您的验证码为123456，该验证码5分钟内有效。请勿泄漏于他人。","UTF-8"));
		String body = sb.toString() + HttpUtil.createCommonParam(Config.ACCOUNT_SID, Config.AUTH_TOKEN);
	    
	    String url = Config.BASE_URL;// + operation;
	   // String body = "accountSid=" + accountSid + "&to=" + phone + "&templateid=" + tmpSmsContent
	    //    + HttpUtil.createCommonParam();
	    
	    // 提交请求
	    String result = HttpUtil.post(url, body);
	    
	    //(换行符) 剔除了平台无关性
	    System.out.println("result:" + System.lineSeparator() + result);
	    System.out.println(result.getClass());
	    
	    //字符串转json对象
	    JSONObject jsonObject = JSONObject.parseObject(result); 
	    String respCode = jsonObject.getString("respCode");
	    System.out.println(respCode);
	    
		//反馈-00000状态码标识请求成功，
		String defaultRespCode="00000";
		if(defaultRespCode.equals(respCode)){
			 return defaultRespCode;
		}else{
			return rod;		
		}
	}
}
